#pragma once

#include <iostream>
#include <cstring>
#include <memory>
#include <unistd.h>
#include <functional>
#include <sys/types.h>
#include <wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

#include "Comm.hpp"
#include "Log.hpp"
#include "Inetaddr.hpp"
#include "Threadpool.hpp"

using namespace LogModule;
using namespace ThreadPoolModule;

#define BACKLOG 8
const static uint16_t gport = 8081;

class TcpServer
{
    using handler_t = std::function<std::string(std::string&)>;
    using task_t = std::function<void()>;
    struct ThreadData
    {
        int sockfd;
        TcpServer* self;
    };

public:
    TcpServer(handler_t handler, const uint16_t port = gport)
        :_handler(handler), _port(port), _isrunning(false)
    {
    }

    void InitTcpServer()
    {
        // 1.创建tcp套接字
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            Die(SOCKET_ERROR);
        }
        LOG(LogLevel::INFO) << "socket create success, sockfd is: " << _listensockfd;

        // 2.填充网络信息并bind
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;
        int n = bind(_listensockfd, CONV(&local), sizeof(local));
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            Die(BIND_ERROR);
        }
        LOG(LogLevel::INFO) << "bind success...";

        // 3.tcp是面向连接的，要求tcp随时随地等待被链接
        // tcp需要将socket设置为监听状态
        n = listen(_listensockfd, BACKLOG);
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "listen error";
            Die(LISTTEN_ERROR);
        }
        LOG(LogLevel::INFO) << "listen success...";

        // signal(SIGCHLD, SIG_IGN); // 子进程退出，OS自动回收资源，不用在wait了
    }

    void HandlerRequest(int sockfd)
    {
        char inbuffer[4096];
        std::string package;
        while (true)
        {
            // ssize_t n = read(sockfd, inbuffer, sizeof(inbuffer) - 1);
            ssize_t n = recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (n > 0)
            {
                inbuffer[n] = 0;
                LOG(LogLevel::INFO) << "\n" << inbuffer;
                package += inbuffer;
                // std::string str = "server echo# ";
                // str += inbuffer;
                std::string cmd_result = _handler(package);
                if (cmd_result.empty()) continue;
                // write(sockfd, str.c_str(), str.size());
                send(sockfd, cmd_result.c_str(), cmd_result.size(), 0);
            }
            else if (n == 0) // 表示文件描述符被关闭
            {
                LOG(LogLevel::INFO) << "client quit, sockfd is: " << sockfd;
                break;
            }
            else break;// 读取失败
        }
        close(sockfd);// client退出文件描述符不再需要
    }

    static void *ThreadEntry(void *args)
    {
        // 需要将线程进行分离，线程结束后自动回收
        pthread_detach(pthread_self());
        ThreadData* data = (ThreadData*)args;
        data->self->HandlerRequest(data->sockfd);
        return nullptr;
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 不能直接读取，先获取新链接
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensockfd, CONV(&peer), &len);
            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error, " << strerror(errno);
                continue;
            }
            // 连接成功
            LOG(LogLevel::INFO) << "accept success, sockfd is: " << sockfd;

            InetAddr cli(peer);
            LOG(LogLevel::INFO) << "client info: " << cli.Addr();

            // // version 1
            // HandlerRequest(sockfd);

            // // version 2 
            // pid_t id = fork();
            // if (id == 0) // 子进程
            // {
            //     close(_listensockfd);
            //     if (fork() > 0) exit(0);// 子进程退出
            //     // 子进程的子进程，此时被系统领养
            //     HandlerRequest(sockfd);
            //     exit(0);
            // }
            // // 父进程
            // close(sockfd);
            // // 此时爷孙两进程独立，不再阻塞等待
            // pid_t rid = waitpid(id, nullptr, 0);
            // if (rid < 0)
            // {
            //     LOG(LogLevel::WARNING) << "waitpid error...";
            // }

            // // version 3
            // pthread_t tid;
            // // 需要传递sockfd，但是不能直接传递地址
            // ThreadData* data = new ThreadData;
            // data->sockfd = sockfd;
            // data->self = this;
            // pthread_create(&tid, nullptr, ThreadEntry, data);

            // version 4
            // task_t task = std::bind(&TcpServer::HandlerRequest, this, sockfd);
            // ThreadPool<task_t>::GetInstance()->Equeue(task);
            ThreadPool<task_t>::GetInstance()->Equeue([this, sockfd](){
                this->HandlerRequest(sockfd);
            });
        }
    }

    void Stop()
    {
        _isrunning = false;
    }
    ~TcpServer()
    {
    }

private:
    int _listensockfd; // 监听socket
    bool _isrunning;
    uint16_t _port;

    handler_t _handler; // 需要处理的任务
};